package com.tuanbiao.dialog;

import android.app.Activity;
import android.content.Intent;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.widget.AppCompatButton;

import com.abiao.lib_utils.StringUtils;
import com.hzjq.data.entity.SettingParams;
import com.hzjq.data.entity.UIDRule;
import com.hzjq.data.hzjq.entity.CapRecordEntity;
import com.hzjq.lib.BlastKool;
import com.jakewharton.rxbinding4.view.RxView;
import com.tuanbiao.R;
import com.tuanbiao.base.action.ToastAction;
import com.tuanbiao.models.action.DetonatorAction;
import com.tuanbiao.ui.CaptureActivity;
import com.tuanbiao.utils.ClickUtil;
import com.tuanbiao.utils.MediaUtils;
import com.tuanbiao.utils.Utils;
import com.tuanbiao.widget.ClearEditText;

import java.util.concurrent.TimeUnit;

/**
 * @author abiao
 * @date 2022/9/9 9:41
 * @description:
 */
public class InsertDetonatorStartEndDialog extends BaseDialogFragment implements ToastAction, DetonatorAction {
    private ClearEditText etStartUid;
    private ImageView ivScanStart;
    private ClearEditText etEndUid;
    private ImageView ivScanEnd;
    private AppCompatButton btnCancel;
    private AppCompatButton btnConfirm;
    private OnConfirmListener listener;
    private ActivityResultLauncher<Intent> launcherStart = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
            , result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    if (result.getData() != null)
                        etStartUid.setText(result.getData().getStringExtra(Utils.BAR_CODE));
                } else {
                    showShort("相机打开出错，请稍后重试");
                }
            });
    private ActivityResultLauncher<Intent> launcherEnd = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
            , result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    if (result.getData() != null)
                        etEndUid.setText(result.getData().getStringExtra(Utils.BAR_CODE));
                } else {
                    showShort("相机打开出错，请稍后重试");
                }
            });

    public InsertDetonatorStartEndDialog setListener(OnConfirmListener listener) {
        this.listener = listener;
        return this;
    }

    public static InsertDetonatorStartEndDialog newInstance() {
        InsertDetonatorStartEndDialog fragment = new InsertDetonatorStartEndDialog();
        return fragment;
    }

    @Override
    protected void initViews(View view) {
        SettingParams settings = BlastKool.Companion.loader().quick().getSettings();
        etStartUid = (ClearEditText) view.findViewById(R.id.et_start_uid);
        ivScanStart = (ImageView) view.findViewById(R.id.iv_scan_start);
        etEndUid = (ClearEditText) view.findViewById(R.id.et_end_uid);
        ivScanEnd = (ImageView) view.findViewById(R.id.iv_scan_end);
        btnCancel = (AppCompatButton) view.findViewById(R.id.btn_cancel);
        btnConfirm = (AppCompatButton) view.findViewById(R.id.btn_confirm);
        etStartUid.setFilters(new InputFilter[]{new InputFilter.LengthFilter(settings.getUidRule() == UIDRule.QH214 ? 27 : 13)});
        etEndUid.setFilters(new InputFilter[]{new InputFilter.LengthFilter(settings.getUidRule() == UIDRule.QH214 ? 27 : 13)});
        RxView.clicks(ivScanStart)
                .throttleFirst(3000, TimeUnit.MICROSECONDS)
                .subscribe(unit -> launcherStart.launch(CaptureActivity.createIntent(InsertDetonatorStartEndDialog.this)));
        RxView.clicks(ivScanEnd)
                .throttleFirst(3000, TimeUnit.MICROSECONDS)
                .subscribe(unit -> launcherEnd.launch(CaptureActivity.createIntent(InsertDetonatorStartEndDialog.this)));
        btnCancel.setOnClickListener(v -> {
            if (null != listener) listener.onCancel();
            dismiss();
        });
        btnConfirm.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            String start = getString(etStartUid);
            if (TextUtils.isEmpty(start)) {
                showShort("请输入起始编码");
                return;
            }

            if (settings.getUidRule() == UIDRule.QH214) {
                boolean b = start.length() == 13 || start.length() == 27;
                if (!b) {
                    showShort("请输入13或27位雷管编码");
                    return;
                }
                if (start.length() == 27) {
                    start = start.substring(14);
                } else {
                    CapRecordEntity entity = new CapRecordEntity();
                    entity.setConvertUid(start);
                    String duid = BlastKool.Companion.getCapUidConvertor().restore(entity);
                    entity.setUid(duid);
                    start = BlastKool.Companion.getCapUidConvertor().convert(entity);
                }
            } else {
                if (start.length() != 13) {
                    showShort("请输入13位雷管编码");
                    return;
                }
            }

            if (StringUtils.isContainChinese(start)) {
                showShort("编码不能包含汉字");
                return;
            }
            String end = getString(etEndUid);
            if (TextUtils.isEmpty(end)) {
                showShort("请输入结束编码");
            }

            if (settings.getUidRule() == UIDRule.QH214) {
                boolean b = end.length() == 13 || end.length() == 27;
                if (!b) {
                    showShort("请输入13或27位雷管编码");
                    return;
                }
                if (end.length() == 27) {
                    end = end.substring(14);
                } else {
                    CapRecordEntity entity = new CapRecordEntity();
                    entity.setConvertUid(end);
                    String duid = BlastKool.Companion.getCapUidConvertor().restore(entity);
                    entity.setUid(duid);
                    end = BlastKool.Companion.getCapUidConvertor().convert(entity);
                }
            } else {
                if (end.length() != 13) {
                    showShort("请输入13位雷管编码");
                    return;
                }
            }

            if(start.isEmpty() || end.isEmpty()){
                showShort("管壳码不正确");
                return;
            }


            if (StringUtils.isContainChinese(end)) {
                showShort("编码不能包含汉字");
                return;
            }
            if (!TextUtils.equals(start.substring(0, 11), end.substring(0, 11))) {
                showShort("请确保起始编码与结束编码的盒号一致！");
                return;
            }
            if (!TextUtils.isDigitsOnly(start.substring(8))) {
                showShort("请确保起始编码最后5位是数字");
                return;
            }

            if (!TextUtils.isDigitsOnly(end.substring(8))) {
                showShort("请确保结束编码最后5位是数字");
                return;
            }
            int startIndex = Integer.parseInt(start.substring(8));
            int endIndex = Integer.parseInt(end.substring(8));
            if (startIndex >= endIndex) {
                showShort("请确保起始编码流水号小于结束编码的流水号");
                return;
            }

            if (!isCorrectDisplayUid(start) || !isCorrectDisplayUid(end)) {
                showShort("编码错误");
                MediaUtils.playSound(R.raw.code_error);
                return;
            }
            if (null != listener) listener.onConfirm(this, start, end);
            dismiss();
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.dialog_detonator_insert_start_end;
    }

    public interface OnConfirmListener {
        void onConfirm(BaseDialogFragment dialogFragment, String start, String end);

        void onCancel();
    }
}
